package org.example;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.SecurityFilterChain;
import de.codecentric.boot.admin.server.config.AdminServerProperties;

@Configuration
public class AdminSecurityConfig {

    private final String adminContextPath;

    // 注入Admin服务端上下文路径（默认是空，即/）
    public AdminSecurityConfig(AdminServerProperties adminServerProperties) {
        this.adminContextPath = adminServerProperties.getContextPath();
    }

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        // 允许服务端自身注册和访问actuator端点
        http.authorizeHttpRequests(auth -> auth
                // 允许所有对actuator端点的访问（包括自身）
                .requestMatchers("/instances/**", "/actuator/**","/actuator/loggers/**", "/actuator/logfile/**").permitAll()  // 允许注册和监控端点
                // 允许客户端注册接口（服务端自身注册会调用此接口）
                .requestMatchers(adminContextPath + "/instances/**").permitAll()
                // 允许Admin页面静态资源
                .requestMatchers(adminContextPath + "/assets/**").permitAll()
                // 允许登录页面
                .requestMatchers(adminContextPath + "/login").permitAll()
                // 其他请求需要认证
                .anyRequest().authenticated()
        );

        // 表单登录（Admin页面登录用）
        http.formLogin(form -> form.loginPage(adminContextPath + "/login"));

        // 开发环境禁用CSRF（避免注册时被拦截）
        http.csrf(csrf -> csrf.disable());

        return http.build();
    }
}

